package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.model.search.vos.SearchArticleVo;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;

import java.io.IOException;

/**
 * @author ybw
 * @version 1.0
 * @date 2021/12/21 20:35
 */
public class SearchListener {
  @Autowired private RestHighLevelClient restHighLevelClient;
  /**
   * 新增文章之后新增索引库
   *
   * @param message
   */
  @KafkaListener(topics = "search_update")
  public void listener(String message) {
    try {
      SearchArticleVo vo = JSON.parseObject(message, SearchArticleVo.class);
      IndexRequest indexRequest = new IndexRequest("app_info_article");
      indexRequest.id(vo.getId().toString()).source(message, XContentType.JSON);
      // 将索引添加到es索引库
      restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
